//
//  HROrderApplyViewController.m
//  haierapp
//
//  Created by gaotangzhang on 14-8-18.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HROrderApplyViewController.h"

#import "HROrderApplyCell.h"

#import "HROrderApplyHeader.h"
#import "HROrderApplyFooter.h"

#define HEIGHT_HEADER_CELL 40.0f

#define HEIGHT_CELL 80.0f

#define CELL_IDENTIFIER @"orderapplycell"

@interface HROrderApplyViewController (){
    
    NSDictionary *_returnMoney;
    NSDictionary *_returnGoods;
    
    int _curOptionIndex;//当前选中 申请的选项
    int goodsCount;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;


@property (weak, nonatomic) IBOutlet UITableView *orderTableView;


@property (weak, nonatomic) IBOutlet UILabel *fTitle;
@property (weak, nonatomic) IBOutlet UITableView *optionTableView;

@property (weak, nonatomic) IBOutlet UILabel *sTitle;

@property (weak, nonatomic) IBOutlet UITextField *explainTextField;
@property (weak, nonatomic) IBOutlet UIButton *uploadImageButton;

@property (weak, nonatomic) IBOutlet UIButton *applyButton;

@end

@implementation HROrderApplyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (_applyType==APPLY_TYPE_AFTERSALE) {
        self.title=@"售后申请";
    }else{
        self.title=@"退款申请";
    }

    
    _returnGoods=@{@"title":@"售后类型",
                   @"option":@[@"维修",@"换货",@"退货"]};
    
    _returnMoney=@{@"title":@"退款原因",
                   @"option":@[@"我不想买了!",@"商家缺货",@"其他原因"]};
    
    
    _curOptionIndex=0;//默认为第一个选项
    
    UIImage *imagebg=[[UIImage imageNamed:@"border_dotted"]resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [_uploadImageButton setBackgroundImage:imagebg forState:UIControlStateNormal];
    
    UIImage *btnBg=[[UIImage imageNamed:@"orange_btn"]resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [_applyButton setBackgroundImage:btnBg forState:UIControlStateNormal];
    
    //订单商品表的高度定义
    [self orderTableAdaptHeight];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Methods
//隐藏键盘
- (IBAction)onTapHideKeyboard:(id)sender {

    [self.explainTextField resignFirstResponder];
}

-(void)selectOptionAction:(id)sender{
    UIButton *button=(UIButton *)sender;
    _curOptionIndex=button.tag;
    
    [self.optionTableView reloadData];
}

//提交申请
- (IBAction)onTapApplySubmit:(id)sender {
    
    ORDER_APPLY_TYPE type=ORDER_APPLY_TYPE_REPAIR;
    
    if (_applyType==APPLY_TYPE_AFTERSALE) {
        //售后
        NSString *typeStr=[[_returnGoods objectForKey:@"option"]objectAtIndex:_curOptionIndex];
        
        if ([typeStr isEqualToString:@"维修"]) {
            type=ORDER_APPLY_TYPE_REPAIR;
        }else if ([typeStr isEqualToString:@"换货"]){
            type=ORDER_APPLY_TYPE_CHANGE;
        }else{
            type=ORDER_APPLY_TYPE_RETURN;
        }
        
    }
    
    NSString *reason=_explainTextField.text;
    
    if ([reason isEqualToString:@""] || reason==nil) {
        [self showTextHUD:@"请填写退款说明"];
        return;
    }
    
    ORDER_APPLY_ADDR_TYPE addrType=ORDER_APPLY_ADDR_TYPE_ORIGIN;
    
    HROrderProductInfo *product=[_order.productList objectAtIndex:0];

    
    
    NSString *orderNo=_order.orderNo;
    NSString *productId=[product.productId stringValue];
    NSString *productNum=product.productNum;
    
    
    [self showCustomLoadingHud:kLoading inView:nil];
    
    [HRInterfaceManager repairOrderApplyByOrder:orderNo withReason:reason withType:type withAddrType:addrType withProductId:productId withProductCount:productNum completion:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            [self showSuccessHud:@"申请提交成功!"];
            
            //更新订单
            [HRCommonData shareCommonData].hasNewOrder=YES;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [self showTextHUD:message];
        }
        
        
    }];

}

//订单商品表自适应高度
-(void)orderTableAdaptHeight{
    int count;
    
    if(_order.productList!=nil && [_order.productList count]>0){
        count=[_order.productList count];
    }else{
        count=0;
    }
    
    NSArray *constraints=[_orderTableView constraints];
    
    for (NSLayoutConstraint *constraint in constraints) {
        if (constraint.firstAttribute==NSLayoutAttributeHeight) {
            CGFloat height=HEIGHT_CELL*count + 80;
            constraint.constant=height;
        }
    }
    
}

//上传图片
- (IBAction)onTapUploadImage:(id)sender {
    
    UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:@"请选择要上传的图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选取",@"拍照", nil];
    
    
    [actionSheet showInView:self.view];
}

//选择上传的图片
- (void)takePictureFromCamera:(BOOL)flag{
    
    if (flag) {
        //检查相机模式是否可用
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            NSLog(@"sorry, no camera or camera is unavailable.");
            return;
        }
        //获得相机模式下支持的媒体类型
        NSArray* availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        BOOL canTakePicture = NO;
        for (NSString* mediaType in availableMediaTypes) {
            if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
                //支持拍照
                canTakePicture = YES;
                break;
            }
        }
        //检查是否支持拍照
        if (!canTakePicture) {
            NSLog(@"sorry, taking picture is not supported.");
            return;
        }
    }
    
    
    //创建图像选取控制器
    UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
    
    if (flag) {
        //设置图像选取控制器的来源模式为相机模式
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        //设置图像选取控制器的类型为静态图像
        imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString*)kUTTypeImage, nil];
    }else{
        imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    //允许用户进行编辑
    imagePickerController.allowsEditing = YES;
    //设置委托对象
    imagePickerController.delegate = self;
    //以模视图控制器的形式显示
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

//创建订单 中的商品CELL
-(UITableViewCell *)createOrderGoodsCell:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HROrderApplyCell *cell=[tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];
    
    if (cell==nil) {
        cell=[[HROrderApplyCell alloc]init];
    }
    
    HROrderProductInfo *product=[_order.productList objectAtIndex:indexPath.row];
    
    [cell configWithData:product];
    
    return cell;
}

//创建 申请 选项 cell
-(UITableViewCell *)createOptionCell:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIndentifier=@"applyOptionCell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        UIButton *radioButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 37)];
        radioButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;

        UIImage *selectedImage=[UIImage imageNamed:@"radio"];
        UIImage *unSelectedImage=[UIImage imageNamed:@"radio_d"];
        [radioButton setImage:selectedImage forState:UIControlStateSelected];
        [radioButton setImage:unSelectedImage forState:UIControlStateNormal];
        cell.accessoryView=radioButton;
        
        [radioButton addTarget:self action:@selector(selectOptionAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    NSDictionary *applyOption;
    
    if (_applyType==APPLY_TYPE_AFTERSALE) {
        applyOption=_returnGoods;
    }else{
        applyOption=_returnMoney;
    }
    
    NSArray *options=[applyOption objectForKey:@"option"];
    NSString *optionInfo=[options objectAtIndex:indexPath.row];
    
    cell.textLabel.font=[UIFont fontWithName:FONT_NAME_DEFAULT size:12.0f];
    cell.textLabel.textColor=[UIColor colorFromHexRGB:@"303030"];
    cell.textLabel.text=optionInfo;
    
    UIButton *button=(UIButton *)cell.accessoryView;
    button.tag=indexPath.row;
    [button setSelected:NO];
    
    if (indexPath.row==_curOptionIndex) {
        [button setSelected:YES];
    }
    
    return cell;
}

#pragma mark - TablView DataSource Delegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    int count=0;
    
    if(tableView==_orderTableView){
        
        if (_order.productList!=nil && [_order.productList count]>0) {
            count=[_order.productList count];
        }
        
        return count;
    }else{
        NSDictionary *applyOption;
        
        if (_applyType==APPLY_TYPE_AFTERSALE) {
            applyOption=_returnGoods;
        }else{
            applyOption=_returnMoney;
        }
        
        
        return [[applyOption objectForKey:@"option"]count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell;
    
    if (tableView==_orderTableView) {
        
       cell=[self createOrderGoodsCell:tableView cellForRowAtIndexPath:indexPath];
        
    }else{
       
        cell=[self createOptionCell:tableView cellForRowAtIndexPath:indexPath];
    }
    
    return cell;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    HROrderApplyHeader *headerView=[[HROrderApplyHeader alloc]initWithType:APPLY_HEADER_TITLE_DESC showTopLine:YES];
    headerView.titleLabel.text=[NSString stringWithFormat:@"订单号:%@",_order.orderNo];
    
    headerView.descLabel.text=_order.orderStateStr;
    
    return headerView;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    HROrderApplyFooter *footerView=[[HROrderApplyFooter alloc]initWithShowBottomLine:YES AndShowSeperateView:NO];

    footerView.orderNo=_order.orderNo;
    
    int count=[_order.productList count];
    footerView.goodsCountLabel.text=[NSString stringWithFormat:@"共%d件商品",count];
    
    footerView.goodsTotalPriceLabel.text=[NSString stringWithFormat:@"￥%@",_order.totalPrice];
    
    return footerView;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView==_orderTableView) {
        return HEIGHT_CELL;
    }else{
        return 37.0f;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView==_orderTableView) {
        return HEIGHT_HEADER_CELL;
    }else{
        return 0.0f;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView==_orderTableView) {
        return HEIGHT_FOOTER_ORDERCELL_NORMAL;
    }else{
        return 0.0f;
    }
}




#pragma mark - TableView Delegate Methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (tableView==_optionTableView) {
        _curOptionIndex=indexPath.row;
        [_optionTableView reloadData];
    }
}

#pragma mark - ActionSheet Delegate Methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (buttonIndex==0) {
        //从相册选取
        [self takePictureFromCamera:NO];
        
    }else if(buttonIndex==1){
        //拍照
        [self takePictureFromCamera:YES];
    }
}


#pragma mark - UIImagePicker Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (__CUR_IOS_VERSION < __IPHONE_7_0) {
        [self solveCompatible];
    }
   
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (__CUR_IOS_VERSION < __IPHONE_7_0) {
        [self solveCompatible];
    }
 
}

//解决，在ios6下，scrollview移位
-(void)solveCompatible{
    
    //获取商品数
    CGFloat constant=84.5 + (goodsCount-1)*40;

    NSArray *lcArray=_scrollView.constraints;
    NSLog(@"%f",_contentView.frame.origin.y);
    for (NSLayoutConstraint *lc in lcArray) {
        if (lc.firstItem==_contentView && lc.firstAttribute==NSLayoutAttributeTop) {
            lc.constant=constant;
        }
    }

}

#pragma mark - UITextField Delegate Method
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


@end
